<!--
 * @description  : 案件-证据先行登记保存权利告知书
 * @descriptionDetail: 案件-证据先行登记保存权利告知书
 * @copyright    : 福建烟草
 * @author       : zyf
 * @create       : 2024-03-28 17:10:00
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" backText="返回">
      <view class="theme-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit ? "预览" : "打印" }}
      </view>
    </theme-navbar>
    <!-- #endif -->
    <!-- #ifdef H5-WECHAT || H5-EMP -->
    <fab-button :content="state.canEdit ? fContent : fContents" @fabtrigger="fabtrigger" />
    <!-- #endif -->
    <view class="main-content">
      <view style="width: calc(100% + 30px)">
        <form-section title="证据先行登记保存权利告知书"></form-section>
      </view>
      <u-form class="form-content" :model="docIns" :error-type="errorType" ref="uForm">
        <u-form-item label="告知书日期" :label-width="labelWidth" :required="true" right-icon="arrow-right" prop="apvDate" ref="dateChangeRef">
          <u-input
            :disabled="true"
            placeholder="请选择日期"
            input-align="right"
            v-model="docIns.apvDate"
            @click="
              () => {
                if (state.canEdit) isShowDate = true;
              }
            "
          />
        </u-form-item>
        <u-form-item label="告知书" :label-width="labelWidth" :label-position="labelPosition" :required="true" prop="goodsRegFullDocNo" ref="regDocRef">
          <u-input :clearable="false" :disabled="!state.canEdit" placeholder="请输入" v-model="docIns.goodsRegFullDocNo" type="textarea" />
        </u-form-item>
        <u-form-item label="当事人" :label-position="labelPosition" prop="party" :required="true" right-icon="arrow-right">
          <u-input
            placeholder="请输入"
            :disabled="true"
            v-model="docIns.party"
            @click="
              () => {
                if (state.canEdit) partySelectShow = true;
              }
            "
          />
        </u-form-item>
        <u-form-item label="案由" :label-position="labelPosition" prop="causeOfAction" ref="caseChangeRef">
          <u-input
            type="textarea"
            height="35"
            :auto-height="true"
            placeholder=""
            :disabled="true"
            v-model="docIns.causeOfAction"
            @click="
              () => {
                if (state.canEdit) causeOfActionHandle();
              }
            "
          />
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-title">
                执法人员（执法证号）
              </view>
              <view
                class="uicon-sty"
                @click="
                  () => {
                    if (state.canEdit) addPerson();
                  }
                "
              >
                <u-icon name="plus-circle" :color="$theme.u_type_primary" size="40"></u-icon>
              </view>
            </view>
            <view class="p-content" v-for="(item, index) in personList" :key="index">
              <text class="p-width">{{ item.personName }}：</text>
              <text>
                {{ item.leCertNo || item.inspectionCertNo }}
              </text>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="文书日期" label-width="200" right-icon="arrow-right" :required="true" ref="docDateChangeRef">
          <u-input
            :disabled="true"
            placeholder="请选择日期"
            input-align="right"
            v-model="docIns.docDate"
            @click="
              () => {
                if (state.canEdit) isShowDocDate = true;
              }
            "
          />
        </u-form-item>
      </u-form>
    </view>
    <view class="space-content"></view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="saveOrSubmit('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="saveOrSubmit('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-calendar :mode="mode" :max-date="maxDate" v-model="isShowDate" @change="changeDate('apvDate', $event)"></u-calendar>
    <u-calendar :mode="mode" :max-date="yestDate" v-model="isShowDocDate" @change="changeDate('docDate', $event)"></u-calendar>
    <!-- 当事人选择 -->
    <u-popup mode="bottom" height="80%" v-model="partySelectShow" z-index="990">
      <select-party-component :params="partyParams" @choose="handlerChooseParty"></select-party-component>
    </u-popup>
  </view>
</template>
<script>
import { dateUtils } from "@/common/util";
import PersonSelection from "@/pages/case/components/personSelection.vue";
import caseCommon from "../caseCommonMixin.js";
import DicChoice from "@/components/dic_choice.vue";
import DicInput from "@/components/dic_input.vue";
import officeService from "@/service/case/office.service.js";
import caseService from "@/service/case/case.service";
import SelectPartyComponent from "../components/selectPartyComponent.vue";
import FormSection from "@/components/form-section.vue";
import fabButton from "@/components/uni-fab.vue";
export default {
  components: {
    PersonSelection,
    SelectPartyComponent,
    FormSection,
    DicChoice,
    DicInput,
    fabButton,
  },
  mixins: [caseCommon],
  data() {
    return {
      mode: "date",
      maxDate: "2099-12-31",
      isShowDate: false,
      isShowDocDate: false,
      importLicShow: false,
      labelPosition: "top",
      labelWidth: "360",
      errorType: ["border-bottom", "message"],
      personSelectShow: false,
      psParam: {},
      regsList: [], // 告知书列表
      fContent: [
        {
          iconPath: require("@/static/oview.png"),
          selectedIconPath: require("@/static/oview.png"),
          text: "预览",
          active: false,
        },
      ],
      fContents: [
        {
          iconPath: require("@/static/dy.png"),
          selectedIconPath: require("@/static/dy.png"),
          text: "打印",
          active: false,
        },
      ],
      rules: {
        apvDate: [
          {
            required: true,
            message: "请选择告知书日期",
            trigger: ["change", "blur"],
          },
        ],
        goodsRegFullDocNo: [
          {
            required: true,
            message: "请输入告知书",
            trigger: ["change", "blur"],
          },
        ],
        docDate: [
          {
            required: true,
            message: "请选择文书日期",
            trigger: ["change", "blur"],
          },
        ],
      },
      personList: [], // 执法人员
      isAction: false,
      caseParam: {}, // 文书列表中传过来的参数
      doc: {},
      docIns: {},
      docRegsInfo: [],
      selectRegs: {},
      saveData: {},
      checkIndex: 0,
      isShowSignView: false,
      signImgList: [],
      goodsList: [],
      partySelectShow: false,
      partyList: [], // 当事人列表
      partyParams: {}, // 传给当事人选择页面的参数
      yestDate: this.$u.timeFormat(Date.now()),
      goodsRightUuid: "",
    };
  },
  watch: {
    isShowDocDate() {
      this.$refs.dateChangeRef.validation();
    },
    isShowDate() {
      this.$refs.docDateChangeRef.validation();
    },
    isAction() {
      this.$refs.caseChangeRef.validation();
    },
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(data) {
    this.caseParam = this.getRouteParam();
  },
  mounted() {
    this.docStep((docInfo) => {
      this.doc = docInfo ? docInfo : {};
      this.setRightBtns();
    });
    this.initDocData();
  },
  methods: {
    // 设置右侧标题
    setRightBtns() {
      // #ifdef H5-DINGDING
      this.$deviceApi.setRight(
        this.state.canEdit ? "预览" : "打印",
        () => {
          this.printOrDown(this.state.canEdit);
        },
        true,
        true
      );
      // #endif
    },
    // 初始化文书信息
    initDocData() {
      let parms = {
        id: this.caseParam.id,
        docUuid: this.caseParam.docUuid,
        bizUuid: this.caseParam.bizUuid,
      };

      this.$u.loading("加载中...");
      officeService
        .docGoodsRight(parms)
        .then((res) => {
          let rs = {};
          let goodsRegFullDocNo = "";
          if (res.success && res.data.length === 2) {
            goodsRegFullDocNo = res.data[0].goodsRegFullDocNo || "";
            rs = res.data[1];
          } else {
            rs = res.data[0];
            goodsRegFullDocNo = res.data[0].goodsRegFullDocNo || "";
          }
          this.docIns = rs;
          this.docIns.goodsRegFullDocNo = goodsRegFullDocNo;
          this.docIns.apvDate = rs.apvDate ? rs.apvDate : dateUtils.dateFormat("yyyy年MM月dd日", new Date());
          this.docIns.docDate = rs.docDate ? rs.docDate : dateUtils.dateFormat("yyyy年MM月dd日", new Date());
          let employeeList = this.parseEmployee(rs);
          this.personList = employeeList;
          this.getPartyInfoList();
        })
        .catch((er) => {
          console.log(er);
          this.$u.hideLoading();
          this.$u.toast(er);
        });
    },
    // 获取当事人list（多选）
    getPartyInfoList() {
      caseService
        .getPartyInfoList(this.caseParam.bizUuid)
        .then((res) => {
          this.$u.hideLoading();
          if (!res.success) return;
          let names = [];
          this.partyList = res.data.length > 0 ? res.data : [];
          this.partyList.forEach((itm) => {
            if (this.docIns.partyUuids.indexOf(itm.partyUuid) != -1) {
              itm.check = true;
              names.push(itm.partyName);
            }
          });
          this.docIns.party = names.join(",");
          this.partyParams = {
            list: this.partyList,
            selUsersStr: this.docIns.partyUuids,
          };
        })
        .catch((err) => {
          this.partyList = [];
          console.log(err);
        });
    },
    // 选择当事人回调事件
    handlerChooseParty(e) {
      this.partySelectShow = false;
      this.docIns.party = e.partyNames;
      this.partyParams.selUsersStr = e.partyUuids;
      this.docIns.partyUuids = e.partyUuids;
    },
    changeDate(type, e) {
      this.docIns[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
      if (type == "docDate") this.$refs.docDateChangeRef.validation();
      if (type == "apvDate") this.$refs.dateChangeRef.validation();
    },
    // 打印/预览
    printOrDown(flag) {
      if (flag) {
        // 调接口预览
        this.saveOrSubmit("preview");
      } else {
        this.downloadFile(this.doc.pdfFileId);
      }
    },
    downloadFile(fileId, titleName, isDownload) {
      let pdfIds = fileId;
      if (!pdfIds) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({
        fileId: pdfIds,
        fileName: titleName,
        isDownload: isDownload,
      });
      this.$u.route("pages/commonPage/printerComponent");
    },
    // 添加执法人员事件
    addPerson() {
      this.psParam = {
        min: 2,
        max: 2,
        caseUuid: this.caseParam.caseUuid,
      };
      this.personSelectShow = true;
    },
    handlerChoosePerson(e) {
      this.personSelectShow = false;
      this.personList = [...e];
      let tIds = [];
      let tNames = [];
      this.personList.forEach((el) => {
        tIds.push(el.personUuid);
        tNames.push(el.personName + "(" + el.leCertNo + ")");
      });
      this.docIns["undertakerUuids"] = tIds.join(",");
      this.docIns["undertaker"] = tNames.join(",");
    },
    checkboxChange(e) {
      console.log(e);
      this.docIns.handleDesc01 = e.join(",");
    },
    // 案由点击事件
    causeOfActionHandle() {
      this.isAction = true;
      this.$u.route("pages/case/components/casePropertySelection");
    },
    // 选择案由返回列表时更新列表状态
    updateBackState(param) {
      // 案由
      if (param.caseSelectionData) {
        let [names, ids] = [[], [], [], []];
        param.caseSelectionData.forEach((item) => {
          names.push(item.caseProperty);
          ids.push(item.casepropUuid);
        });
        this.$set(this.docIns, "causeOfAction", names.join(","));
        this.$set(this.docIns, "casepropIds", ids.join(","));
        this.isAction = false;
      }
    },
    // 表单验证
    validForm() {
      let basicValid = false;
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (!this.docIns.partyUuids) {
            this.$u.toast("请选择当事人!");
            return;
          }
          basicValid = true;
        } else {
          basicValid = false;
        }
      });
      return basicValid;
    },
    // 保存或提交
    saveOrSubmit(type) {
      if (type == "preview") {
        if (!this.doc.isRecorded) {
          this.$u.toast("请先保存数据");
          return;
        }
        officeService.buildLocalPunish("/record/doc-goods-handle", this.doc.docInsUuid).then((pdfId) => {
          if (pdfId.success) {
            this.downloadFile(pdfId.bean, "预览", false);
          } else {
            this.$u.toast(pdfId.msg);
          }
        });
      } else {
        let flag = this.validForm();
        if (flag) {
          if (this.personList.length == 0) {
            this.$u.toast("请选择执法人员!");
            return;
          }
          if (!this.docIns.docNo) {
            this.$u.toast("文书编号不能为空!");
            return;
          }
          if (!this.docIns.docYear) {
            this.$u.toast("文书年份不能为空!");
            return;
          }
          if (this.docIns.docNo.length > 20) {
            this.$u.toast("文书编号请输入20位以内的字符!");
            return;
          }
          if (this.docIns.docYear.length > 4) {
            this.$u.toast("文书年份请输入4位数之内!");
            return;
          }

          this.handleOperBtn(type);
        }
      }
    },
    fabtrigger(btn) {
      if (btn.index == 0) {
        this.printOrDown(this.state.canEdit);
      }
    },
    handleOperBtn(flag) {
      let [docGoodsRight, self] = [this.docIns, this];
      let { docUuid, id, titemUuid, type, bizUuid, caseCode, caseType, gfaCode } = this.caseParam;
      docGoodsRight.caseUuid = this.caseParam.caseUuid;
      flag === "save" && this.$u.loading("数据保存中...");
      officeService.saveDocGRight(docGoodsRight, docUuid, titemUuid, id, type).then((res) => {
        this.$u.hideLoading();
        if (res.success) {
          this.$u.toast(res.msg);
          let bean = res.bean;
          docGoodsRight.goodsRightUuid = bean.goodsRightUuid;
          this.saveData = res.data[0];
          self.doc["isRecorded"] = res.data[0].isRecorded;
          self.doc["docInsUuid"] = res.data[0].docInsUuid;
          this.docIns = docGoodsRight;
          if (flag === "submit") {
            this.$u.loading("数据提交中...");
            officeService
              .submitDocRight(bean, docUuid, titemUuid)
              .then((res) => {
                this.$u.hideLoading();
                this.saveBehaviorLog(1, this.caseParam, this.doc);
                if (res.success) {
                  // 返回列表
                  this.$u.toast(res.msg);
                  self.backPrev({
                    paramKey: "offiList",
                    param: {
                      caseUuid: bizUuid,
                      caseCode: caseCode,
                      caseType: caseType,
                    },
                  });
                } else {
                  this.$u.toast(res.msg);
                }
              })
              .catch((er) => {
                console.log(er);
                this.$u.hideLoading();
                this.$u.toast(er);
              });
          } else {
            this.saveBehaviorLog(0, this.caseParam, this.doc);
          }
        } else {
          this.$u.toast(res.msg);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../case_common.scss";

.page {
  padding: 0;
}

.doc-no {
  display: inline-block;
  height: 35px;
  width: 60px;
  text-align: center !important;
  flex: none;
}

.check-desc {
  display: flex;
  align-items: center;

  .dec-input {
    width: 25%;
  }
}
</style>
